﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Chart;
using Atmk.WaterMeter.MIS.Entities.Enums;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic.Statistics
{
    public class OwnersLogic : IOwnersLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IOwnerRepository _ownerRepository;
        private readonly IMeterRepository _meterRepository;
        private readonly IMeterReadingRepository _meterReadingRepository;

        public OwnersLogic(
            IOwnerRepository ownerRepository,
            IMeterRepository meterRepository,
            IMeterReadingRepository meterReadingRepository
        )
        {
            _ownerRepository = ownerRepository;
            _meterRepository = meterRepository;
            _meterReadingRepository = meterReadingRepository;
        }

        /// <summary>
        /// 获取关阀业主信息
        /// </summary>
        /// <param name="leafDistrictIds"></param>
        /// <returns></returns>
        public ClosingvalveData GetCloseClosingValveOwnerItems(params string[] leafDistrictIds)
        {
            //获取所有片区下业主信息
            var owners = _ownerRepository.GetOwners(leafDistrictIds);
            //获取该业主下所有水表号
            var meters = _meterRepository.GetMetersByOwnerIds(owners.Select(o => o.Id.ToString()).ToArray()).ToList();
            //获取该业主集合下所有关阀的表编号
            var closingValveMeterNumber =
                _meterReadingRepository
                    .NowDataMeterReadingRecords(meters.Select(m => m.MeterNumber).ToList(), DateTime.Now)
                    .Where(r => r.ValveState == (int)ValveState.Closed).Select(m => m.CtdeviceId);
            //获取关阀的业主信息集合
            var list = owners.Where(o =>
                meters.Where(m => closingValveMeterNumber.Contains(m.MeterNumber)).Select(m => m.OwnerId)
                    .Contains(o.Id.ToString())).Select(o => new ClosingValveOwnerItem
            {
                ownerId = o.Id.ToString(),
                ownerName = o.Name,
                houseNumber = o.HouseNumber
            }).ToList();
            return new ClosingvalveData {total = list.Count.ToString(), list = list};
        }
    }
}